package p.ithorns.tools.translator.sdk;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.stereotype.Component;
import p.ithorns.tools.translator.annotation.Translatable;
import p.ithorns.tools.translator.sdk.core.TranslateCore;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 转换器AOP
 *
 * @author R
 * @date 2022-9-27
 */
@Aspect
@Component
@Order(2)
public class TranslatorAspect {

    @Resource
    private GenericConversionService genericConversionService;

    @AfterReturning(
            pointcut = "@annotation(p.ithorns.tools.translator.annotation.Translatable)",
            returning = "returnValue"
    )
    public void doAfter(JoinPoint point, Object returnValue) {
        if (null != returnValue) {
            // 获取容器中的转换器进行返回值解包，注意此处返回结果可能是Bean也可能是集合
            Object result = genericConversionService.convert(returnValue, Object.class);

            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            Translatable translatable = method.getAnnotation(Translatable.class);

            TranslateCore.translate(result, translatable);
        }
    }

}